<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class Findpwd extends Controller
{
    public function findpwd(){
        $newpassword=mt_rand(11111111,99999999);
        $data['password']=md5('tmd'.$newpassword);
        $data['time']=time();
        $admin=Db::name('admin')->where('id',1)->find();
        if($admin){
            if(time()<$admin['time']+60){
                return json(['code' => 500,'msg' => '不要频繁操作']);
            }
            $res=Db::name('admin')->where(array('id'=>1))->update($data);
        }else{
            return json(['code' => 500,'msg' => '失败']);
        }
        $allinfo='天虎物流新密码:'.$newpassword;
        $result=$this->send_mail('1796270459@qq.com','oijunxsvmxvkechi','找回密码',$allinfo);
        if($result){
            return json(['code' => 200,'msg' => '成功']);
        }else{
            return json(['code' => 500,'msg' => '失败!']);
        }
    }
    private function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) {

        $mail = new \PHPMailer\PHPMailer\PHPMailer();           //实例化PHPMailer对象
        $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
        $mail->IsSMTP();                    // 设定使用SMTP服务
        $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
        $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
        $mail->SMTPSecure = 'ssl';          // 使用安全协议
        $mail->Host = "smtp.qq.com"; // SMTP 服务器
        $mail->Port = 465;                  // SMTP服务器的端口号
        $mail->Username = $tomail;    // SMTP服务器用户名
        $mail->Password =$name;     // SMTP服务器密码，这里是你开启SMTP服务时生成密码
        $mail->SetFrom($tomail, '自己!');
        $replyEmail = '';                   //留空则为发件人EMAIL
        $replyName = '';                    //回复名称（留空则为发件人名称）
        $mail->AddReplyTo($replyEmail, $replyName);
        $mail->Subject = $subject;
        $mail->MsgHTML($body);
        $mail->AddAddress($tomail,'自己');
        if (is_array($attachment)) { // 添加附件
            foreach ($attachment as $file) {
                is_file($file) && $mail->AddAttachment($file);
            }
        }
        return $mail->Send() ? true : $mail->ErrorInfo;
    }

}